package jmine.tec.persist.schema.impl.parsers;

import java.util.regex.Matcher;

import jmine.tec.persist.schema.impl.elements.AlternateKeyElement;
import jmine.tec.persist.schema.impl.elements.Schema;

/**
 * Parser de alternate keys
 * 
 * @author lundberg
 */
public class AlternateKeyParser extends AbstractSchemaElementParser<AlternateKeyElement> {

    private static final int TABLE_NAME_GROUP_INDEX = 1;

    private static final int AK_NAME_GROUP_INDEX = 2;

    private static final int AK_COLUMNS_GROUP_INDEX = 3;

    /**
     * Construtor
     * 
     * @param schema o schema
     */
    public AlternateKeyParser(Schema schema) {
        super("alter\\s+table\\s+(" + TableParser.TABLE_NAME_REGEX  + ")\\s+add\\s+constraint\\s+(\\w+)\\s+unique\\s+\\(([\\w\\s,]+)\\)", schema);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public AlternateKeyElement doParse(Matcher matcher) {
        String table = matcher.group(TABLE_NAME_GROUP_INDEX);
        String akName = matcher.group(AK_NAME_GROUP_INDEX);
        AlternateKeyElement ak = new AlternateKeyElement(getSchema());
        ak.setTable(table);
        ak.setName(akName);
        for (String columnName : matcher.group(AK_COLUMNS_GROUP_INDEX).replaceAll("\\s", "").split(",")) {
            ak.addColumn(columnName);
        }
        return ak;
    }
}
